﻿using System; 
using System.Web.UI; 
using System.Text;
using System.IO;
using System.Globalization;
using SiteUnity.Layers.Application.Contents;
using SiteUnity.Layers.Entity.PageItems.Contents;
using SiteUnity.Layers.Application.BaseClasses;

namespace SiteUnity.Frame.Modules
{
    [ToolboxData("<{0}:PageContent runat=server/>")]
    public class PageContent : BaseWebControl
    {
        public HtmlTextWriterTag TitleHtmlTag { get; set; }
        public HtmlTextWriterTag TextHtmlTag { get; set; }
        public ContentType Type { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Type == default(ContentType))
                Type = ContentType.FullText;
        }

        private void generatePageContent(HtmlTextWriter output)
        {
            foreach (Content content in ContentManager.getContentByPage())
                if (Type == content.TypeID)
                {
                    if (!string.IsNullOrEmpty(content.ContentTitle))
                    {
                        if (TitleHtmlTag == HtmlTextWriterTag.Unknown)
                            output.Write(content.ContentTitle);
                        else
                        {
                            output.RenderBeginTag(TitleHtmlTag);
                            output.Write(content.ContentTitle);
                            output.RenderEndTag();
                        }
                    }

                    if (TextHtmlTag == HtmlTextWriterTag.Unknown)
                        output.Write(content.ContentText);
                    else
                    {
                        output.RenderBeginTag(TextHtmlTag);
                        output.Write(content.ContentText);
                        output.RenderEndTag();
                    }
                }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb, CultureInfo.InvariantCulture));
            generatePageContent(htw);

            output.Write(sb.ToString());
        }
    }
}
